<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>title</title>
  <script src="./js/vue.js"></script>
  <style>
    table{
        border: 1px solid #e9e9e9;
        border-collapse: collapse;
        border-spacing: 0;
    }
    th,td{
        padding: 8px 16px;
        border: 1px solid #e9e9e9;
        text-align: left;
    }
    th{
        background-color: #f7f7f7;
        color:black;
        font-weight: 600;
    }
  </style>
</head>
<body>
<div id="app">
  <div v-if="books.length">
    <table>
      <thread>
        <tr>
          <th>id</th>
          <th>商品名称</th>
          <th>商品价格</th>
          <th>商品数量</th>
          <th>操作</th>
        </tr>
      </thread>
      <tbody>
      <tr v-for="(book, index) in books" :key="book">
        <td>{{index+1}}</td>
        <td>{{book.name}}</td>
        <td>{{book.price | showPrice}}</td>
        <td>
          <button @click="decrease(index)" :disabled="book.count <= 0">-</button>
          {{book.count}}
          <button @click="increase(index)">+</button>
        </td>
        <td>
          <button @click="removeClick(index)">移除</button>
        </td>
      </tr>
      </tbody>
    </table>
    <h2>总价：{{totalPrice | showPrice}}</h2>
  </div>
  <h2 v-else>购物车为空</h2>
</div>
<script>
  const app = new Vue({
    el: "#app",
    data: {
      books: [
        {"name":"充电宝","price":99.111, "count": 0},
        {"name":"小风扇","price":88.222, "count": 0},
        {"name":"小音箱","price":125.533, "count": 0},
        {"name":"蓝牙耳机","price":315.344, "count": 0},
      ],
    },
    methods: {
      decrease(index){
        this.books[index].count-=1
      },
      increase(index){
        this.books[index].count+=1
      },
      removeClick(index){
        this.books.splice(index, 1)
      }
    },
    computed: {
      totalPrice(){
        let totalPrice = 0
        for (let item of this.books){
          totalPrice += item.price * item.count
        }
        return totalPrice
      }
    },
    filters: {
      showPrice(price){
        return '￥' + price.toFixed(2)
      }
    }
  })
</script>
</body>
</html>